package ui;

import bean.Files;
import service.IFileService;
import utils.Constants;
import utils.PictureUtil;

import javax.swing.*;
import javax.swing.border.EmptyBorder;

import com.alee.laf.tabbedpane.WebTabbedPane;

import java.awt.*;
import java.awt.event.*;
import java.util.List;

public class SearchPanel extends JPanel {
    private JTextField searchText;
    private JLabel searchButton;
    private JPopupMenu resultPopup;
    private JList<Files> resultList;
    private DefaultListModel<Files> listModel;
    private IFileService fileService;
    private WebTabbedPane menuInfo;
    private Files selectedFile;
    
    public void setSelectedFile(Files file) {
    	this.selectedFile=file;
    }
    public Files getSelectedFile() {
    	return this.selectedFile;
    }
    public void setMenuInfo(WebTabbedPane menuInfo) {
    	this.menuInfo=menuInfo;
    }
    
    private static Color defaultBgColor = Color.WHITE;
    
    public SearchPanel(IFileService fileService,WebTabbedPane menu) {
        this.fileService = fileService;
        this.menuInfo=menu;
        initUI();
    }

    private void initUI() {
        setLayout(null);
        setOpaque(false);
        setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.GRAY),
                new EmptyBorder(0, 5, 0, 5)));

        // 搜索文本框
        searchText = new JTextField("");
        searchText.setText(Constants.SPACE + Constants.SEARCH_TXT);
        searchText.setOpaque(false);
        searchText.setFocusable(false);
        searchText.setBounds(0, 3, 200, 30);
        searchText.setBorder(BorderFactory.createEmptyBorder());
        add(searchText);

        // 搜索按钮
        searchButton = new JLabel();
        searchButton.setBounds(200, 3, 45, 30);
        searchButton.setOpaque(false);
        searchButton.setBackground(defaultBgColor);
        searchButton.setIcon(PictureUtil.getPicture("search_icon.png"));
        add(searchButton);

        // 初始化结果列表
        listModel = new DefaultListModel<>();
        resultList = new JList<>(listModel);
        resultList.setCellRenderer(new FileListCellRenderer());
        resultList.setFixedCellHeight(30); // 设置行高
        resultList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 初始化弹出菜单
        resultPopup = new JPopupMenu();
        resultPopup.setBorder(BorderFactory.createLineBorder(Color.GRAY));
        resultPopup.add(new JScrollPane(resultList));
        
        //加载事件监听方法
        initListener();
    }

    private void initListener() {
        // 搜索框鼠标事件
        searchText.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (Constants.SEARCH_TXT.equals(searchText.getText().trim())) {
                    activateSearchField();
                }
            }
        });
     // 搜索框焦点事件
        searchText.addFocusListener(new FocusAdapter() {
        	@Override
        	public void focusLost(FocusEvent e) {
        		searchText.setOpaque(false);
        		searchText.setFocusable(false);
        		searchText.setText(Constants.SPACE + Constants.SEARCH_TXT);
        		searchText.updateUI();
        		searchButton.setOpaque(false);
        		searchButton.updateUI();
        	}
        });
        // 搜索按钮点击
        searchButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                performSearch();
            }
        });

        // 回车键搜索
        searchText.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    performSearch();
                }
            }
        });

        // 列表点击事件
        resultList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    //设置为Files对象，在MainUI用到
                	setSelectedFile(resultList.getSelectedValue());
                    if (selectedFile != null) {
                    	//返回一个文件，在MainUI中重定位
                    	relocateFile(selectedFile);
                        resultPopup.setVisible(false);
                    }
                }
            }
        });
    }

    private void activateSearchField() {
        searchText.setOpaque(true);
        searchText.setFocusable(true);
        searchText.requestFocus();
        searchText.setText("");
    }

    private void performSearch() {
        String keyword = searchText.getText().trim();
        if (keyword.isEmpty() || Constants.SEARCH_TXT.equals(keyword)) {
            resultPopup.setVisible(false);
            return;
        }

        List<Files> results = fileService.searchFilesByName(keyword);
        showResults(results);
    }

    private void showResults(List<Files> results) {
        listModel.clear();
        
        if (results.isEmpty()) {
            listModel.addElement(new Files("无结果", "", null, ""));
        } else {
            results.forEach(listModel::addElement);
        }
        
        // 调整列表大小
        int rowCount = Math.min(results.size(), 10);
        int height = rowCount * resultList.getFixedCellHeight();
        resultList.setVisibleRowCount(rowCount);
        
        // 显示弹出菜单
        resultPopup.show(searchText, 0, searchText.getHeight());
        resultPopup.setPopupSize(searchText.getWidth(), height + 4); // +4 补偿边框
    }
    
    public void relocateFile(Files f) {
		System.out.println("进入到重定位");
		String folderId = f.getFolderId();
		String filepath = f.getFilePath();	        
		// 1. 找到对应的选项卡
		System.out.println("tabCount:"+menuInfo.getTabCount());
		for (int i = 0; i < menuInfo.getTabCount(); i++) {
			FilePanel panel = (FilePanel) menuInfo.getComponentAt(i);
			if (panel.getFolder().getFolderId().equals(folderId)) {
				// 切换到该选项卡
				menuInfo.setSelectedIndex(i);	                
				// 2. 在文件列表中定位到特定文件
				JList<Files> fileList = panel.getFileList();
				DefaultListModel<Files> model = (DefaultListModel<Files>) fileList.getModel();                
				// 查找文件在列表中的位置
				for (int j = 0; j < model.size(); j++) {
					Files item = model.getElementAt(j);
					if (item.getFilePath() != null && item.getFilePath().equals(filepath)) {
						// 3. 高亮显示该文件
						fileList.setSelectedIndex(j);
						fileList.ensureIndexIsVisible(j); // 确保可见

						// 设置高亮颜色
						fileList.setSelectionBackground(new Color(70, 130, 180)); // 深蓝色
						fileList.setSelectionForeground(Color.WHITE);
						break;
					}
				}
				break;
			}
		}
    
	}

}